<?php
namespace app\erp_meixingtiyu\model;

use think\Model;
use think\model\concern\SoftDelete;
use app\erp_meixingtiyu\model\TimeTemplate as TimeTemplateModel;
use app\erp_meixingtiyu\model\Referee as RefereeModel;

class Arena extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $table = 'athlon_arena';
    protected $pk = 'arena_id';

    public function parts()
    {
        return $this->hasMany(ArenaPart::class);
    }

    public function timeTemplate()
    {
        return $this->belongsTo(TimeTemplate::class);
    }

    public function sessions()
    {
        return $this->hasManyThrough(
            ArenaPartTimeFragment::class,
            ArenaPart::class
        );
    }

    // 添加场地
    public function createArena($data)
    {
        self::create($data);
    }

    // 获取所有场地及其半场信息
    public static function getAllArenasWithParts()
    {
        return self::with(['parts', 'parts.fragments'])->select();
    }

    // 获取指定场地及其半场信息
    public function getArenaWithPartsById($arenaId)
    {
        return self::with('parts')->find($arenaId);
    }

    // 更新场地信息及其半场时段
    public function updateArenaInfo($params, $isChangeTemplate)
    {
        $this->transaction(function () use ($params, $isChangeTemplate) {
            // 更新该场地信息
            $this->save($params);
            // 若时段模板有改变，替换掉该场地下的所有半场的时段关联
            if ($isChangeTemplate) {
                $template = TimeTemplateModel::find(
                    $params['time_template_id']
                );

                // 获取新模板下所有的时段id
                $fragments_id = [];
                foreach ($template->fragments as $fragment) {
                    $fragments_id[] = $fragment->time_fragment_id;
                }

                foreach ($this->parts as $part) {
                    // 删除与之前模板的所有时段关联
                    $part->fragments()->detach($part->fragments);
                    // 关联新模板的所有时段
                    $part->fragments()->attach($fragments_id, [
                        'status' => $template->status,
                        'price' => $template->price,
                    ]);
                }
            }
        });
    }

    // 获取一页场地及其时段模板信息
    public function getArenasWithTimeTemplateByPaginate()
    {
        return $this->with(['timeTemplate'])
            ->order('sort', 'asc')
            ->paginate(15);
    }
}
